package com.example.casesys.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.casesys.dto.UserDTO;
import com.example.casesys.dto.UserDTOPlus;
import com.example.casesys.entity.User;
import com.example.casesys.mapper.UserMapper;
import com.example.casesys.service.UserService;
import com.example.casesys.utils.JwtUtil;
import com.example.casesys.utils.RegexUtils;
import com.example.casesys.utils.UserHolder;
import com.example.casesys.vo.Result;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hongren
 * @since 2023-09-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Result register(User user) {
        String accounts = user.getAccounts();
        String userId = user.getUserId();
        String password = user.getPasswords();
        if (RegexUtils.isNumberInvalid(accounts)) {
            return Result.fail().message("用户账号格式错误！");
        }
        if (RegexUtils.isIdNumber(userId)) {
            return Result.fail().message("身份证号码格式错误！");
        }
        if (RegexUtils.isPassword(password)) {
            return Result.fail().message("密码格式错误！");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("accounts", accounts);
        User user1 = userMapper.selectOne(wrapper);
        if (user1 != null) {
            return Result.fail().message("用户账号已存在！");
        }
        userMapper.insert(user);
        return Result.ok().message("用户注册成功");
    }

    /**
     * 用户登录功能
     *
     * @param user 用户对象
     */
    @Override
    public Result login(User user, HttpSession session) {
        String accounts = user.getAccounts();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accounts", accounts);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) {
            return Result.fail().message("该账号用户不存在！");
        }
        String password = user1.getPasswords();
        String passwords = user.getPasswords();
        if (!passwords.equals(password)) {
            return Result.fail().message("用户输入的密码错误！");
        }
        String token = JwtUtil.createToken(user1.getId());
        user1.setToken(token);
        UserDTO userDto = BeanUtil.copyProperties(user1, UserDTO.class);
        UserHolder.saveUser(userDto, session);
        return Result.ok(userDto);
    }

    /**
     * 超级管理员任命管理员
     * @param id
     * @return
     */
    @Override
    public Result updateType(int id) {
        User user = userMapper.selectById(id);
        Integer accType = user.getAccType();
        if (accType == 1) {
            return Result.ok().message("该用户已是管理员！");
        }
        user.setAccType(1);
        userMapper.updateById(user);
        return Result.ok().message("管理员设定成功");
    }

    /**
     * 超级管理员查询所有用户信息
     * @return
     */
    @Override
    public Result queryAllUser(Integer currentPage, HttpSession session) {
        Integer accType = UserHolder.getUser(session).getAccType();
        if(accType != 2) {
            return Result.fail().message("您不是超级管理员，您无权限！");
        }
        Integer pageSize = 13;
        List<UserDTO> userDTOList = new ArrayList<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("acc_type",2);
        IPage<User> page = new Page(currentPage, pageSize);
        IPage<User> iPage = userMapper.selectPage(page, queryWrapper);
        if(iPage.getTotal() == 0){
            return Result.fail().message("未查询到用户！");
        }
        List<User> userList = iPage.getRecords();
        for (User user : userList) {
            UserDTO userDto = BeanUtil.copyProperties(user, UserDTO.class);
            userDTOList.add(userDto);
        }
        UserDTOPlus userDTOPlus = new UserDTOPlus();
        userDTOPlus.setUserDTOList(userDTOList);
        userDTOPlus.setUserCount(iPage.getTotal());
        return Result.ok(userDTOPlus);
    }

    /**
     * 超级管理员删除用户信息
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        userMapper.deleteById(id);
        return Result.ok().message("删除成功");
    }

    /**
     * 用户修改密码
     * @param user
     * @return
     */
    @Override
    public Result updatePasswordBySelf(User user, HttpSession session) {
        Integer userId = UserHolder.getUser(session).getId();
        User user1 = userMapper.selectById(userId);
        if(!user.getPasswords().equals(user1.getPasswords())){
            return Result.fail().message("原密码错误！");
        }
        String newPassword = user.getNewPassword();
        if(RegexUtils.isPassword(newPassword)){
            return Result.fail().message("新密码格式错误!");
        }
        user1.setPasswords(newPassword);
        userMapper.updateById(user1);
        return Result.ok().message("修改成功");
    }

    /**
     * 超级管理员修改用户信息
     * @param user
     * @return
     */
    @Override
    public Result updateUser(User user) {
        String passwords = user.getPasswords();
        if(passwords != null){
            if(RegexUtils.isPassword(passwords)){
                return Result.fail().message("密码格式错误!");
            }
        }
        userMapper.updateById(user);
        return Result.ok().message("修改成功");
    }

    /**
     * 管理员查询本单位用户信息
     * @return
     */
    @Override
    public Result selectUser(Integer currentPage, HttpSession session) {
        UserDTO userDTO = UserHolder.getUser(session);
        String department = userDTO.getDepartment();
        Integer id = userDTO.getId();
        Integer accType = userDTO.getAccType();
        if(accType != 1){
            return Result.fail().message("您不是管理员，您无权限！");
        }
        Integer pageSize = 13;
        List<UserDTO> userDtoList = new ArrayList<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("department", department);
        wrapper.ne("id",id);
        wrapper.eq("acc_type",0);
        IPage<User> page = new Page(currentPage, pageSize);
        IPage<User> userIPage = userMapper.selectPage(page, wrapper);
        if(userIPage.getTotal() == 0){
            return Result.fail().message("未查询到用户！");
        }
        List<User> userList = userIPage.getRecords();
        for (User user : userList) {
            UserDTO userDto = BeanUtil.copyProperties(user, UserDTO.class);
            userDtoList.add(userDto);
        }
        UserDTOPlus userDTOPlus = new UserDTOPlus();
        userDTOPlus.setUserDTOList(userDtoList);
        userDTOPlus.setUserCount(userIPage.getTotal());
        return Result.ok(userDTOPlus);
    }

    /**
     * 管理员修改本单位用户信息
     * @param user
     * @return
     */
    @Override
    public Result updateByAdministrator(User user) {
        String passwords = user.getPasswords();
        if(passwords != null) {
            if (RegexUtils.isPassword(passwords)) {
                return Result.fail().message("密码格式错误！");
            }
        }
        userMapper.updateById(user);
        return Result.ok().message("修改成功");
    }

    /**
     * 管理员删除本单位的用户信息
     * @param id
     * @return
     */
    @Override
    public Result deleteByAdministrator(Integer id) {
        userMapper.deleteById(id);
        return Result.ok();
    }

    /**
     * 超级管理员移除管理员的权限
     * @param id
     * @return
     */
    @Override
    public Result removeAdministrator(Integer id) {
        User user = userMapper.selectById(id);
        Integer accType = user.getAccType();
        if(accType != 1){
            return Result.fail().message("当前用户不是管理员！");
        }
        user.setAccType(0);
        userMapper.updateById(user);
        return Result.ok().message("修改成功");
    }

    /**
     * 用户查看个人信息
     * @return
     */
    @Override
    public Result selectSelf(HttpSession session) {
        UserDTO user = UserHolder.getUser(session);
        return Result.ok(user);
    }


}